import type { Request, Response } from "express";
import { getMarketDataService } from "../services/MarketData";

/**
 * GET /api/market/quotes
 * 获取所有股票行情
 */
export const getAllMarketQuotes = (_req: Request, res: Response) => {
  const marketService = getMarketDataService();
  const quotes = marketService.getAllQuotes();

  res.json({
    quotes: quotes.map((q) => ({
      ...q,
      timestamp: q.timestamp.toISOString(),
    })),
    updatedAt: new Date().toISOString(),
  });
};

/**
 * GET /api/market/quote/:symbol
 * 获取指定股票的行情
 */
export const getMarketQuote = (req: Request, res: Response) => {
  const { symbol } = req.params;

  if (!symbol) {
    return res.status(400).json({ error: "symbol 参数是必填的" });
  }

  const marketService = getMarketDataService();
  const quote = marketService.getQuote(symbol);

  if (!quote) {
    return res.status(404).json({ error: "未找到该股票" });
  }

  res.json({
    quote: {
      ...quote,
      timestamp: quote.timestamp.toISOString(),
    },
    updatedAt: new Date().toISOString(),
  });
};

/**
 * GET /api/market/history/:symbol
 * 获取股票价格历史
 * query: ?limit=100
 */
export const getPriceHistory = (req: Request, res: Response) => {
  const { symbol } = req.params;
  const limit = req.query.limit
    ? parseInt(req.query.limit as string, 10)
    : 100;

  if (!symbol) {
    return res.status(400).json({ error: "symbol 参数是必填的" });
  }

  if (isNaN(limit) || limit < 1 || limit > 1000) {
    return res
      .status(400)
      .json({ error: "limit 必须是 1-1000 之间的数字" });
  }

  const marketService = getMarketDataService();
  const history = marketService.getPriceHistory(symbol, limit);

  res.json({
    symbol,
    history: history.map((h) => ({
      ...h,
      timestamp: h.timestamp.toISOString(),
    })),
    count: history.length,
    updatedAt: new Date().toISOString(),
  });
};




